package com.ljw.store.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.dialect.Ingres10Dialect;

import com.ljw.store.entity.Store;
import com.ljw.store.services.StoreService;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class StoreAction extends ActionSupport{
	private static int BUFFER_SIZE = 16 * 1024;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src));
				out = new BufferedOutputStream(new FileOutputStream(dst));
				byte[] buffer = new byte[BUFFER_SIZE];

				while (in.read(buffer) > 0) {
					out.write(buffer);
				}

			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static int getBUFFER_SIZE() {
		return BUFFER_SIZE;
	}
	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);

	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	public static void setBUFFER_SIZE(int bUFFER_SIZE) {
		BUFFER_SIZE = bUFFER_SIZE;
	}
	private List<Store> allStore;
	private Object imageFileName;
	private int pageNumber;
	private int pageSize;
	int shopId;
	private Store store;
	private File storePicture;
	private String storePictureContentType;
	private String storePictureFileName;
	@Resource
	private StoreService storeService;
	private int totalPage;
	public String addStore(){	
		// TODO Auto-generated method stub
		imageFileName = new Date().getTime() + getExtention(storePictureFileName);
		final String path = ServletActionContext.getServletContext().getRealPath("/adminView/adminImage");
		File dir = new File(path);
		if(!dir.exists())
			dir.mkdirs();
		File imageFile = new File(path + "/" + imageFileName);
		copy(storePicture, imageFile);
		store.setPicture("adminView/adminImage/" + imageFileName);
		storeService.saveStore(store);
		return SUCCESS;
	}
	public String delStore() {
		//HttpServletRequest request = ServletActionContext.getRequest();
		//Integer shopId = Integer.parseInt(request.getParameter("shopId"));
		//Store store = new Store();
		//store.setShopId(shopId);
		try {
			//调用HQL语句删除关联的表（）
			storeService.deleteStoreHQL("delete from CartList where shopId= '"+store.getShopId()+"'");
			storeService.deleteStoreHQL("delete from Cart where shopId= '"+store.getShopId()+"'");
			storeService.deleteStoreHQL("delete from Item where shopId= '"+store.getShopId()+"'");
			storeService.deleteStore(store);
			
		} catch (Exception ex) {
			ex.printStackTrace();
			return Action.INPUT;
		} finally {
		}
		return Action.SUCCESS;
	}
	public List<Store> getAllStore() {
		return allStore;
	}
	public Object getImageFileName() {
		return imageFileName;
	}
	public int getPageNumber() {
		return pageNumber;
	}
	public int getPageSize() {
		return pageSize;
	}
	public int getShopId() {
		return shopId;
	}
	public Store getStore() {
		return store;
	}
	public File getStorePicture() {
		return storePicture;
	}
	public String getStorePictureContentType() {
		return storePictureContentType;
	}
	public String getStorePictureFileName() {
		return storePictureFileName;
	}
	public StoreService getStoreService() {
		return storeService;
	}
	public int getTotalPage() {
		return totalPage;
	}
	public void setAllStore(List<Store> allStore) {
		this.allStore = allStore;
	}
	public void setImageFileName(Object imageFileName) {
		this.imageFileName = imageFileName;
	}
	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public void setShopId(int shopId) {
		this.shopId = shopId;
	}
	public void setStore(Store store) {
		this.store = store;
	}
	public void setStorePicture(File storePicture) {
		this.storePicture = storePicture;
	}
	public void setStorePictureContentType(String storePictureContentType) {
		this.storePictureContentType = storePictureContentType;
	}
	public void setStorePictureFileName(String storePictureFileName) {
		this.storePictureFileName = storePictureFileName;
	}
	public void setStoreService(StoreService storeService) {
		this.storeService = storeService;
	}
	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
	public String showStore() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader( "Pragma", "no-cache" );  
		response.setDateHeader("Expires", 0);  
		response.addHeader( "Cache-Control", "no-cache" );  
		response.addHeader( "Cache-Control", "no-store" );  
		response.addHeader( "Cache-Control", "must-revalidate" );
		String pageNumberStr = request.getParameter("pageNumber");
		if (pageNumberStr == null || "".equals(pageNumberStr.trim())) {
			pageNumberStr = "1";
		}
		pageSize = 8;
		int storeAmount = storeService.storeAmount();
		/*
		 * storeAmount:记录数据库中的Store数目
		 * pageSize：规定一页显示的Store数目
		 * pageNumberStre：你�?��前往的页面页�?
		 */
		int[] paging = new int[2];
		System.out.println(paging);
		paging = storeService.pageNumber(storeAmount, pageNumberStr, pageSize);
		pageNumber = paging[0];
		totalPage = paging[1];
		/*
		 pageNumber方法返回的paging[]
		 paging[0]：你�?��前往的正确页面页�?
		 paging[1]：�?共的页数
		 pageNumber在jsp页面出现两种特殊情况
		 �?、如果在第一页，点击上一页，pageNumber=0
		 ②�?如果在最后一页，点击下一�?pageNumber=totalPage+1
		            �?��pageNumber在①、pageNumber=1
		                                                 在②、pageNumber=totalPage
		 */
		try{
			allStore = storeService.searchAllStore(pageNumber, pageSize);
		}catch(Exception ex){
			ex.printStackTrace();
			return Action.INPUT;
		}finally{
		}
		for (Store showStore : allStore) {
			System.out.println("名字"+showStore.getShopName());
		}
		return Action.SUCCESS;
	}
	public String toUpdStore(){
		List<Store> list = storeService.searchStore(store);
		store=list.get(0);
		return SUCCESS;
	}
	
	public String updStore(){
		System.out.println("####"+store.getShopId());
		Store storeTemp = new Store();
		List<Store> listTemp = storeService.searchStore(store);
		for(Store storeTemp2 : listTemp){
		    storeTemp = storeTemp2;
		}
		final String path = ServletActionContext.getServletContext()
				.getRealPath("/adminView/adminImage");
		
		File imageFile = new File(path + "/" + storeTemp.getPicture().replace("adminView/adminImage/", ""));
		if(storePicture != null){
			copy(storePicture, imageFile);
		}
		store.setPicture(storeTemp.getPicture());
		try{
		storeService.updateStore(store);
		}catch(Exception ex){
			ex.printStackTrace();
			return Action.INPUT;
		}
		finally{
		}
		return Action.SUCCESS;
	}
	//展示热门商店
	public String showhotStore() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumberStr = request.getParameter("pageNumber");
		if (pageNumberStr == null || "".equals(pageNumberStr.trim())) {
			pageNumberStr = "1";
		}
		pageSize = 8;
		int storeAmount = storeService.storeAmount();
		int[] paging = new int[2];
		System.out.println(paging);
		paging = storeService.pageNumber(storeAmount, pageNumberStr, pageSize);
		pageNumber = paging[0];
		totalPage = paging[1];
		try{
			allStore = storeService.HotsearchAllStore(pageNumber, pageSize);
		}catch(Exception ex){
			ex.printStackTrace();
			return Action.INPUT;
		}finally{
		}
		return Action.SUCCESS;
	}
	/*s***********************************c*/
	public void validateAddStore() {
        System.out.println("aaaa");
		if (this.store.getLoginName() == null
				|| "".equals(this.store.getLoginName().trim())) {
			// 添加错误信息
			this.addFieldError("loginName", "登录名不能为空");
		}

		if (this.store.getLoginPassword() == null) {
			// 添加错误信息
			this.addFieldError("loginPassword", "密码不能为空");
		}
		if (this.store.getShopName() == null || "".equals(this.store.getShopName().trim())) {
			// 添加错误信息
			this.addFieldError("shopName", "商店名不能为空");
		}
		if (this.storePicture == null) {
			this.addFieldError("storePicture", "图片不能为空");
		}
	}
	public void validateUpdStore() {
        System.out.println("aaaa");
		if (this.store.getLoginName() == null
				|| "".equals(this.store.getLoginName().trim())) {
			// 添加错误信息
			this.addFieldError("loginName", "登录名不能为空");
		}

		if (this.store.getLoginPassword() == null) {
			// 添加错误信息
			this.addFieldError("loginPassword", "密码不能为空");
		}
		if (this.store.getShopName() == null || "".equals(this.store.getShopName().trim())) {
			// 添加错误信息
			this.addFieldError("shopName", "商店名不能为空");
		}
		
	}
	
} 

